﻿using CqCore.Redis;
using SuperShopInfrastructure.Models.Ship;
using SuperShopInfrastructure.Static;
using SuperShopRepository;
using SuperShopService.IServices;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;

namespace SuperShopService.Services
{
    public class SetService : ISetService
    {
        private readonly IRedisService redisService;
        private readonly SetRepository setRepository;

        public SetService(
            IRedisService redisService,
            SetRepository setRepository)
        {
            this.redisService = redisService;
            this.setRepository = setRepository;
        }

        public async Task<ShippingTemplateModel> GetShippingTemplateModel(int id)
        {
            var result = await redisService.GetOrSet<ShippingTemplateModel>("ShippingTemplateModel_" + id, async () =>
              {
                  var ds = await setRepository.GetShippingTemplateModel(id);
                  if (DataManager.CheckDs(ds, 2) && DataManager.CheckHasRow(ds.Tables[0]))
                  {
                      var res = new ShippingTemplateModel();
                      DataRow dr = ds.Tables[0].Rows[0];
                      res.Id = Convert.ToInt32(dr["Id"]);
                      res.ShippingTemplatesName = dr["ShippingTemplatesName"].ToString();
                      res.ChargType = Convert.ToInt32(dr["ChargType"]);
                      if (DataManager.CheckHasRow(ds.Tables[1]))
                      {
                          foreach (DataRow dr_item in ds.Tables[1].Rows)
                          {
                              res.Items.Add(new ShippingTemplateItem()
                              {
                                  Id = Convert.ToInt32(dr_item["Id"]),
                                  ShippingTemplateId = Convert.ToInt32(dr_item["ShippingTemplateId"]),
                                  ProvinceIds = dr_item["ProvinceIds"].ToString(),
                                  FirstValue = Convert.ToInt32(dr_item["FirstValue"]),
                                  NextValue = Convert.ToInt32(dr_item["NextValue"]),
                                  FirstAmount = DataManager.GetRowValue_Decimal(dr_item["FirstAmount"]),
                                  NextAmount = DataManager.GetRowValue_Decimal(dr_item["NextAmount"]),
                                  ProvinceStr = dr_item["ProvinceStr"].ToString(),
                              });
                          }
                      }
                      return res;
                  }

                  return null;
              });
            return result;
        }
    }
}
